package com.pdd.cloud.zuul.fallback;

import com.alibaba.fastjson.JSON;
import com.netflix.client.ClientException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import com.pdd.cloud.zuul.enums.HttpResponse;
import com.pdd.commons.response.ResponseResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author:liyangpeng
 * @date:2019/7/2 21:10
 */
@Component
public class ServerFallBack implements FallbackProvider {

    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        cause.printStackTrace();
        if(cause instanceof HystrixTimeoutException){
            return response(HttpResponse.TIME_OUT);
        }
        if(cause instanceof ClientException){
            return response(HttpResponse.CLIENT_ERROR);
        }
        return null;
    }

    private ClientHttpResponse response(final HttpResponse httpStatus){
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode(){
                return httpStatus.getStatus();
            }

            @Override
            public int getRawStatusCode(){
                return httpStatus.getStatus().value();
            }

            @Override
            public String getStatusText(){
                return httpStatus.getStatus().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody(){
                String message=httpStatus.getMessage();
                String responseBody= JSON.toJSONString(ResponseResult.RETURN_ERROR(message));
                return new ByteArrayInputStream(responseBody.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
